import activityApi from "../../../service/activityApi";
import { reLogin } from '../../../service/request'
const app = getApp()
const SUCCESS_CODE = app.globalData.codeConfig.errCode.SUCCESS_CODE


//计数器
var interval = null;

//值越大旋转时间越长  即旋转速度
var intime = 30;
let interval1; // 广播计数器
Page({
    data: {
        hadAuthFlag: false,
        picBaseUrl: app.globalData.picBaseUrl,
        btnconfirm: "newtwork_luck-draw-btn",
        clickLuck: "clickLuck",
        winningMsgList: [],
        pace: 1,  // 广播滚动速度
        posLeft: 0,  // 广播水平滚动中left值

        luckDrawFlag: false, // 抽奖按钮防止二次点击
        luckPosition: null, // 停止位置
        index: -1,
        lotteryChance: 0, // 抽奖次数
        cardPopup: false,
        luckDrawData: {}, // 奖励卡券
    },

    onLoad: function() {
        // this.loadAnimation();
        this.checkStatus()
        this.lotteryWinningMessages()
        this.getLotteryChance()
        console.log(app.globalData.userInfo, 'userInfo');

    },

    // 登录状态的检查
    checkStatus () {
        let that = this
        // 判断是否有授权，有授权的话从回调调用方法初始化数据
        // 无授权的话直接调用方法初始化数据
        wx.getSetting({
          success: res => {
            if (res.authSetting['scope.userInfo']) {
              that.setData({
                hadAuthFlag: true
              })
            }
          }
        })
    },
    // 授权回调
    bindGetUserInfo (e) {
        console.log(e);
        let that = this
        if (!!e.detail.userInfo) { // 同意授权-并登陆
          wx.setStorageSync('hadAuthFlag', true)
          app.globalData.userInfo = e.detail.userInfo
          app.globalData.hadAuthUserInfo = true
          app.globalData.refreshIndexFlag = true
          reLogin().then(() => {
            that.setData({
              hadAuthFlag: true
            })
            wx.redirectTo({
                url: '../../specialArea/luckDraw/luckDraw'
            })
          })
        } else { // 不同意授权
          wx.setStorageSync('hadAuthFlag', false)
          that.setData({
            hadAuthFlag: false
          })
        }
    },
    // 中奖信息轮播
    lotteryWinningMessages() {
        let that = this;
        activityApi.lotteryWinningMessages().then(res => {
            if (res.data.errCode === SUCCESS_CODE) {
                that.setData({
                    winningMsgList: res.data.data.winningMessages
                })
                // 计算轮播所占元素长度
                let txtLength = 0
                for (var i in that.data.winningMsgList) {
                    txtLength += that.data.winningMsgList[i].length * 13
                }
                that.roll(that, txtLength + 20);
            } else {
                wx.showtoast({
                    title: res.data.msg,
                    icon: 'none'
                })
            }
        })
    },
    // 获取抽奖次数
    getLotteryChance() {
        activityApi.getLotteryChance().then(res => {
            if (res.data.errCode === SUCCESS_CODE) {
                let lotteryChance = res.data.data.lotteryChance - 0
                this.setData({
                    clickLuck: "clickLuck",
                    lotteryChance
                })
                if (lotteryChance === 0) {
                    this.setData({
                        clickLuck: "onNoLuckDraw"
                    })
                }
            } else {
                wx.showtoast({
                    title: res.data.msg,
                    icon: 'none'
                })
            }
        })
    },
    //点击抽奖按钮
    clickLuck() {
        var that = this;
        if (that.data.clickLuck === '') return false
        //设置按钮不可点击
        if (this.data.lotteryChance === 0) return false

        that.setData({
            // btnconfirm: "newtwork_luck-draw-click-btn",
            clickLuck: ''
        });
        //清空计时器
        clearInterval(interval);
        var index = 0;
        //循环设置每一项的透明度
        interval = setInterval(function() {
            if (index > 7) index = 0;
            that.setData({
                index
            });
            index++;
        }, intime);

        
        //请求延迟，防止快速转的时间过短
        var stoptime = 500;
        setTimeout(function() {
            // 抽奖
            activityApi.doLottery().then(res => {
                if (res.data.errCode === SUCCESS_CODE) {
                    let which = res.data.data.prizeInfo.prizeId - 0
                    that.setData({
                        luckDrawData: res.data.data.prizeInfo,
                        lotteryChance: res.data.data.lotteryChance - 0
                    })
                    if (that.data.lotteryChance === 0) {
                        that.setData({
                            clickLuck: "onNoLuckDraw"
                        })
                    }
                    //清空计数器
                    console.log(which, which == 6 ? '大奖' : null);
                    clearInterval(interval);
                    
                    that.stopLuck(which, that.data.index, intime, 50);
                } else {
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none'
                    })
                }
            }).catch(res => {
                //清空计数器
                clearInterval(interval);
            })
        }, stoptime);
    },

    // 抽奖次数用完提示
    onNoLuckDraw() {
        wx.showToast({
            title: '今日抽奖次数已用完，明日再战！',
            icon: 'none'
        })
    },
    /**
     * which:中奖位置
     * index:当前位置
     * time：时间标记
     * splittime：每次增加的时间 值越大减速越快
     */
    stopLuck: function(which, index, time, splittime) {
        var that = this;
        //值越大出现中奖结果后减速时间越长
        setTimeout(function() {
            //重置前一个位置
            if (index > 7) index = 0;
            //当前位置为选中状态
            that.setData({
                index: index
            });
            //如果旋转时间过短或者当前位置不等于中奖位置则递归执行
            //直到旋转至中奖位置
            if (time < 400 || index != which) {
                //越来越慢
                splittime++;
                time += splittime;
                console.log(time);
                //当前位置+1
                index++;
                that.stopLuck(which, index, time, splittime);
            } else {
                //延迟显示弹窗
                setTimeout(function() {
                    that.setData({
                        // btnconfirm: "newtwork_luck-draw-btn",
                        clickLuck: "clickLuck", //设置按钮可以点击
                    });
                    if (which == 1 || which == 2 || which == 4 || which == 6 || which == 7) {
                        let _winningMsgList = that.data.winningMsgList
                        _winningMsgList.unshift(`恭喜${app.globalData.userInfo.nickName}获得${that.data.luckDrawData.property}一张`)
                        that.setData({
                            cardPopup: true,
                            winningMsgList: _winningMsgList
                        });
                        that.selectComponent('#card-ticket-popup').onSetCardData(that.data.luckDrawData)
                    } else {
                        that.setData({
                            luckPosition: which
                        })
                    }
                }, 1000);
            }
        }, time);
    },
    // 关闭未中奖弹窗
    closeNoPrizePopup() {
        this.setData({
            luckPosition: null
        })
    },
    //进入页面时缓慢切换
    loadAnimation: function() {
        var that = this;
        var index = 0;
        interval = setInterval(function() {
            if (index > 7) index = 0
            that.setData({
                index
            });
            index++;
        }, 1000);
    },

    roll(that, txtLength) {
        interval1 = setInterval(function() {
          if (-that.data.posLeft < txtLength) {
            that.setData({
              posLeft: that.data.posLeft - that.data.pace
            })
          } else {
            that.setData({
              posLeft: 20
            })
          }
        }, 20)
    },

    onShow: function() {
        // let that = this;
        // let txtLength = 0
        // for (var i in that.data.winningMsgList) {
        //     txtLength += that.data.winningMsgList[i].length * 13
        // }
        // that.roll(that, txtLength + 120);
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        clearInterval(interval1);
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        clearInterval(interval1);
    }
});